package com.talkyun.utils;

import com.talkyun.utils.codec.Base32;
import com.talkyun.utils.crypt.AesCrypt;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Random;

public class AesCipher {
    private static final AesCipher instance = new AesCipher();
    private static Random random = new SecureRandom();
    private static String[] KEYS = new String[10];

    static {
        KEYS[0] = "x0XHQB9ACW1VZAQ7w9xvHPDlTqD7BsA9wUATi8w0NS6mETkxSSxHpsDj3vkVLxlR";
        KEYS[1] = "KVk2eYyaohK13A10XeNJaAXc9s3lAjWAEraM6WcOq0zWFSQAbEnCrNARKUkOYphg";
        KEYS[2] = "mZgjitKCHyPJ7FeTOnbD1AO0CxMT2q4ZRjm2mqFLNFfcN8IWkaJN9gXq0mbNd61f";
        KEYS[3] = "n00jHoCRLqL3oQm9JssUqqZQX9lVfBq0KkOAfZSokZweP2v6E7sw0JfUj6OZ2g2L";
        KEYS[4] = "g4RaxGho5M69WWhasCHhRFWGWuxlNHuLw1hY0PnI4PLhE52p8VcTCrCj6ANCz3fU";
        KEYS[5] = "lLUlgV5z9DdVBLTQMTDBurRUpRLDmZV5tQMv949d3eIngPmHXXj7Ryzj6adbxYS4";
        KEYS[6] = "zwA49KE8XfOLF2FUSsGshBkGffwXGjm6Affkf9QNVZAvzqDmzX4UurmMH4Cn5zKX";
        KEYS[7] = "biwpVgnsMwvISqQaEhlLNR50zOGWeaqRysoxWoI3cLATUw39FdFFApJVE5i3CNbn";
        KEYS[8] = "RsLWNkaZOmI5kE7uhZs9UzWNX98za0AaQjreUqOdvTgAC8Cc0b72Bsl76ZbXTJR4";
        KEYS[9] = "OLGHFlaVtSCbEmXEC76pMtJIuZFeupDJodc54wsH9NJ7pegeR7ZOvlEWDe8Y4ime";
    }

    public static AesCipher get() {
        return instance;
    }

    public String encrypt(String text) {
        return encrypt(text, "utf-8");
    }

    public String encrypt(String text, String charset) {
        if (text == null) {
            return null;
        }

        int no = random.nextInt(10);
        try {
            byte[] bytes = AesCrypt.encrypt(text.getBytes(charset), KEYS[no]);
            return no + Base32.encode(bytes);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public String decrypt(String text) {
        return decrypt(text, "utf-8");
    }

    public String decrypt(String text, String charset) {
        if (text == null) {
            return null;
        }

        int no = Character.getNumericValue(text.charAt(0));
        byte[] bytes = AesCrypt.decrypt(Base32.decode(text.substring(1)), KEYS[no]);
        try {
            return new String(bytes, charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}